<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\WechatGroup;
use App\Models\WechatGroupUser;
use App\Models\Wechat;
use App\Models\RoleUser;
use DB;
class WechatGroupController extends Controller
{
    protected $fields = [
        'uid' => 0,
        'name' => '',
		'tid' =>0,
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
			$uid = auth()->user()->id;
			$pid = auth()->user()->pid;
          
			//$userids = User::select('id')->where('pid',auth()->user()->id)->get()->toArray();//所有下级uid
			//所有下级id和包括自己的id
			$userids = getCids($uid);
			//查询所有 被授权的id
			$wuserids = WechatGroupUser::select('gid')->where('uid',auth()->user()->id)->get()->toArray();
			 $data['recordsTotal'] = WechatGroup::where(function($query) use($userids,$wuserids){
						$query->whereIn('wechat_groups.uid',$userids)->orWhereIn('wechat_groups.id',$wuserids);
					})->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = WechatGroup::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%');
                })->where(function($query) use($userids,$wuserids){
						$query->whereIn('wechat_groups.uid',$userids)->orWhereIn('wechat_groups.id',$wuserids);
					})->count();
				
                $data['data'] = WechatGroup::select(DB::raw('count(s_wechats.id) as wx_number,(SELECT COUNT(*) FROM s_wechat_group_users WHERE s_wechat_group_users.`gid`=s_wechat_groups.id) kf_number,s_admin_users.name as username,s_wechat_groups.*'))
					->leftJoin("wechats","wechats.group","=","wechat_groups.id")
					->leftJoin("admin_users","admin_users.id","=","wechat_groups.tid")
					->where(function ($query) use ($search) {
						$query->where('wechat_groups.name', 'LIKE', '%' . $search['value'] . '%');
					})
					->where(function($query) use($userids,$wuserids){
						$query->whereIn('wechat_groups.uid',$userids)->orWhereIn('wechat_groups.id',$wuserids);
					})
					->groupBy('id')
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                /* $data['recordsFiltered'] = WechatGroup::where(function ($query) use ($uid){
													if($uid!=1){
														$query->where('uid','=',auth()->user()->id)->orWhere('uid','=',1);
													}
												})->count(); */
				$data['recordsFiltered'] = $data['recordsTotal'];
                $data['data'] = WechatGroup::select(DB::raw('count(s_wechats.id) as wx_number,(SELECT COUNT(*) FROM s_wechat_group_users WHERE s_wechat_group_users.`gid`=s_wechat_groups.id ) kf_number,s_admin_users.name as username,s_wechat_groups.*'))
					->leftJoin("wechats","wechats.group","=","wechat_groups.id")
					->leftJoin("admin_users","admin_users.id","=","wechat_groups.tid")
					->leftJoin("wechat_group_users","wechat_group_users.gid","=","wechat_groups.id")
					//->where('wechat_groups.uid','=',auth()->user()->id)
					->where(function($query) use($userids,$wuserids){
						$query->whereIn('wechat_groups.uid',$userids)->orWhereIn('wechat_groups.id',$wuserids);
					})
					->groupBy('id')
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
		$data['role'] = RoleUser::where('user_id',auth()->user()->id)->first();
        return view('admin.wechatgroup.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
		/* $userList = User::lists('name', 'id');
        $data['userList'] = $userList; */
		//$not_id = User::join('wechat_group_users','wechat_group_users.uid','=','admin_users.id')->where('pid',auth()->user()->id)->where('gid',$gid)->lists( 'admin_users.id');
		$id=0;
		$data['userList'] = User::select('admin_users.name','admin_users.id','wechat_group_users.gid')->leftJoin('wechat_group_users',function ($join)use($id) {
            $join->on('wechat_group_users.uid','=','admin_users.id')->on('gid','=',DB::raw($id));
        })->where('pid',auth()->user()->id)->get();
		$data['role'] = RoleUser::where('user_id',auth()->user()->id)->first();
        return view('admin.wechatgroup.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		if($this->validWechatGroup($request->get('name'),auth()->user()->id!=1?auth()->user()->id:$request->get('uid'))) return redirect('/admin/wechatgroup/create')->withErrors("已有该分组!");
        $wechatgroup = new WechatGroup();
        foreach (array_keys($this->fields) as $field) {
			if($field=='uid'){
				//$wechatgroup->$field = auth()->user()->id;
				$wechatgroup->$field  = getTid(auth()->user()->id);
				continue;
			}
			if($field=='tid'){
				$wechatgroup->$field  = getTid(auth()->user()->id);
				continue;
			}
			$wechatgroup->$field = $request->get($field);
        }
		$wechatgroup->save();
		if (is_array($request->get('usg'))) {
			$datas = [];
			foreach($request->get('usg') as $usg){
				$data['uid'] = $usg;
				$data['gid'] = $wechatgroup->id;
				$datas[] = $data;
			}
			WechatGroupUser::insert($datas);
        }
		if(getRoleName(auth()->user()->id)!='推广员'){//如果不是推广员
			$wechatgroupuser2 = new WechatGroupUser();
			$wechatgroupuser2->uid = auth()->user()->id;
			$wechatgroupuser2->gid = $wechatgroup->id;
			$wechatgroupuser2->save();
		}
		event(new \App\Events\userActionEvent('\App\Models\WechatGroup',$wechatgroup->id, 1, '新增微信分组['.$wechatgroup->name.']' ));
        return redirect('/admin/wechatgroup')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
       $wechatgroup = WechatGroup::find((int)$id);
       if (!$wechatgroup) return redirect('/admin/wechatgroup')->withErrors("找不到该微信号!");
       foreach (array_keys($this->fields) as $field) {
           $data[$field] = old($field, $wechatgroup->$field);
       }
       $data['id'] = (int)$id;
       $data['userList'] = User::select('admin_users.name','admin_users.id','wechat_group_users.gid')->leftJoin('wechat_group_users',function ($join) use($id) {
            $join->on('wechat_group_users.uid','=','admin_users.id')->on('gid','=',DB::raw($id));
        })->where('pid',auth()->user()->id)->get();
		$data['role'] = RoleUser::where('user_id',auth()->user()->id)->first();
       return view('admin.wechatgroup.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
		if($this->validWechatGroup($request->get('name'),auth()->user()->id!=1?auth()->user()->id:$request->get('uid'),$id)) return redirect('/admin/wechatgroup/'.$id.'/edit')->withErrors("已有该分组!");
        $wechatgroup = WechatGroup::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
			if($field=='uid'){
				//$wechatgroup->$field = auth()->user()->id;
				continue;
			}
			if($field=='tid'){
				//$data[$field] = getTid(auth()->user()->id);
				continue;
			}
			if($field=='name'&&$wechatgroup->uid!=auth()->user()->id){
				//$wechatgroup->$field = auth()->user()->id;
				continue;
			}
            $wechatgroup->$field = $request->get($field);
        }
        $wechatgroup->save();
		$wgus = WechatGroupUser::where('gid',$wechatgroup->id)->get();
		$usgs = $request->get('usg',[]);
		$userids = User::select('id')->where('pid',auth()->user()->id)->get()->toArray();
		foreach($userids as $u){
			$us[]=$u['id'];
		}
		foreach($wgus as $wgu){
			if(!in_array($wgu->id,$usgs)){//如果去掉勾，且数据库有数据
				if(in_array($wgu->uid,$us)){
					$wgu->delete();
				}
			}
		}
		$datas = [];
		$wgu = WechatGroupUser::where('gid',$wechatgroup->id)->lists('uid')->toArray();
		foreach($request->get('usg',[]) as $usg){
			if(in_array($usg,$wgu)) continue;
			$data['uid'] = $usg;
			$data['gid'] = $wechatgroup->id;
			$datas[] = $data;
		}
		WechatGroupUser::insert($datas);
       /*  if(getRoleName(auth()->user()->id)!='推广员'){//如果不是推广员
			$wechatgroupuser2 = new WechatGroupUser();
			$wechatgroupuser2->uid = auth()->user()->id;
			$wechatgroupuser2->gid = $wechatgroup->id;
			$wechatgroupuser2->save();
		} */
		event(new \App\Events\userActionEvent('\App\Models\WechatGroup',$id, 3, '更新微信分组['.$wechatgroup->name.']'));
        return redirect('/admin/wechatgroup')->withSuccess('更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(is_numeric($id)){
            $tag = WechatGroup::find((int)$id);
			$name = $tag->name;
            if ($tag) {
				//删掉授权
				WechatGroupUser::where('gid',$id)->delete();
				//Wechat::where('group',$id)->update(['group'=>0]);//分组归类
				//$wechats = Wechat::where('group',$id)->get();
				Wechat::where('group',$id)->delete();
                $tag->delete();
				event(new \App\Events\userActionEvent('\App\Models\WechatGroup',$id, 2, '删除微信分组['.$name.']'));
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }else{
            $idArr = explode(',',$id);
			$names='';
			$wgs = WechatGroup::whereIn('id',$idArr)->get();
			foreach($wgs as $wg){$names.=$wg->name."、";}
            $recordRow =WechatGroup::whereIn('id',$idArr)->delete();
			//删掉授权
			WechatGroupUser::whereIn('gid',$idArr)->delete();
			//Wechat::whereIn('group',$idArr)->update(['group'=>0]);//分组归类
			Wechat::whereIn('group',$idArr)->delete();
			event(new \App\Events\userActionEvent('\App\Models\WechatGroup',0, 2, '删除微信分组['.$names.']'));
            if(!$recordRow){
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }
	public function validWechatGroup($name,$uid,$id=0){
		$count = WechatGroup::where('name','=',$name)->where('uid',$uid)->where('id','<>',$id)->count();
		if($count>0){ //如果已经存在
			return true;
		}else{
			return false;
		}
	}
	public function getUserName($id){
		$user = User::find((int)$id);
		return $user['name'];
	}
	
}